/**
 * creater:chuanpeng.zhu
 * create time:2016/1/20
 * describe：todo
 **/
APP.run(['$ionicPlatform', '$rootScope', 'UserService', '$state', 'CacheService', '$localstorage', '$timeout',
  '$ionicLoading', 'PopupService', '$ionicPopup','PopupService','JpushService',
  function ($ionicPlatform, $rootScope, UserService, $state, CacheService, $localstorage, $timeout,
            $ionicLoading, PopupServic, $ionicPopup,PopupService,JpushService) {

    /** 登录 拦截器 **/
    //$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    //
    //  var state = $state.get(toState.name);
    //  //如果是从login跳入
    //  if (state.requiredLogin && !UserService.isUserLogin()) {
    //    event.preventDefault();
    //    // 跳转到登录前，清空个人信息
    //    UserService.clearUser();
    //    CacheService.set('toState', toState);
    //    CacheService.set('toParams', toParams);
    //    $state.go('login');
    //  }
    //  //如果是从login跳出
    //  if (state.requiredLogin && fromState.name === 'login') {
    //    var newToState = CacheService.get('toState');
    //    var newToParams = CacheService.get('toParams');
    //    if (newToState === '' && newToParams === '') {
    //      event.preventDefault();
    //      $state.go(newToState, newToParams);
    //    }
    //  }
    //});

    /** 登录 拦截器 **/
    $rootScope.$on('REQUIRE_LOGIN', function () {
      // if (!CacheService.get('REQUIRE_LOGIN_SHOW')) {
      //   CacheService.set('REQUIRE_LOGIN_SHOW', true);
      //   PopupService.showConfirm('提示', '尚未登录，是否去登录？', function (res) {
      //     if (res) {
      //       $state.go('login');
      //     } else {
      //       UserService.clearUser();
      //     }
      //     CacheService.set('REQUIRE_LOGIN_SHOW', false);
      //   }, '去登录');
      // }
      $state.go('login');
    });

    /** loading 拦截器 **/
    var requestCount = 0;
    $rootScope.$on('LOADING:SHOW', function () {
      requestCount++;
      if (!$rootScope.isLoadShowing) {
        var params = {
          template: '<div class="loading-div"><img src="./img/sys_loading.svg" style="width: 50px;"/></div>',
          duration: 15000
        };
        $ionicLoading.show(params)
      }
      $rootScope.isLoadShowing = true;
    });

    $rootScope.$on('LOADING:HIDE', function () {
      requestCount--;
      if (requestCount <= 0) {
        $rootScope.isLoadShowing = false;
        $ionicLoading.hide()
      }
    });


    $rootScope.$on('LOCALSTORAGE_FULL', function () {
      var confirmPopup = $ionicPopup.confirm({
        title: '提示',
        okText: '确定',
        cancelText: '取消',
        template: '<span style="font-size: 14px;color: #666">本地图片缓存已满，是否清除缓存？</span><br><span style="font-size: 12px;color: #999999">您还可以在设置中清理缓存。</span>'
      });
      confirmPopup.then(function () {
        $rootScope.$broadcast('CACHE_CLEAR');
      });
    });

    $rootScope.$on('NETWORK:ERROR', function () {
      $timeout(function(){
        PopupService.showToast('网络异常');
      },150);

    });


    $ionicPlatform.ready(function () {

      //判断断网
      //if (window.cordova) {
      //  var networkState = navigator.connection.type;
      //  var states = {};
      //  states[Connection.UNKNOWN] = 'Unknown connection';
      //  states[Connection.ETHERNET] = 'Ethernet connection';
      //  states[Connection.WIFI] = 'WiFi connection';
      //  states[Connection.CELL_2G] = 'Cell 2G connection';
      //  states[Connection.CELL_3G] = 'Cell 3G connection';
      //  states[Connection.CELL_4G] = 'Cell 4G connection';
      //  states[Connection.CELL] = 'Cell generic connection';
      //  states[Connection.NONE] = 'No network connection';
      //  if (networkState == Connection.NONE) {
      //    //$ionicLoading.show({
      //    //  template: '<div class="jsh-loading-text"><span>' + '您的网络未开启' + '</span><br><span>请开启后重新启动</span></div>'
      //    //});
      //    PopupService.showToast('您的网络未开启\n请开启后重新启动');
      //  }
      //}


      $rootScope.isIOS = window.cordova && (ionic.Platform.platform().indexOf('ios') != -1);
      $rootScope.isApp = window.cordova ? true : undefined;
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);

      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
      //通过判断当前是否有cordova决定是否替换window.open
      if (window.cordova && window.cordova.InAppBrowser) {
        window.open = window.cordova.InAppBrowser.open;
      }

      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }


      //拦截android设备物理back键
      $ionicPlatform.registerBackButtonAction(function (e) {
        e.preventDefault();
        showConfirm();
        return false;
      }, 101);

      function showConfirm() {
        var confirmPopup = $ionicPopup.confirm({
          title: '<strong>退出应用</strong>',
          template: '确定要退出应用吗?',
          okText: '退出',
          okType: 'button-balanced',
          cancelText: '取消'
        });
        confirmPopup.then(function (res) {
          if (res) {
            //退出应用
            ionic.Platform.exitApp();
          } else {
            // Don't close
          }
        });
      }

    });


  }])
;
